import { addNum } from 'shiptools'
import { getOrderApi, getCanRefundConfApi, refundTicketApi } from '../../api/index'
import { cleanOrderData, canRefundTicket } from '../order/main'
import {Logger, setPage} from '../../utils/index'
import { SHIP_PASSENGER_TYPE_ORDER, TRACER_PAGES, PRODUCT_CODE } from '../../utils/constants'
const logger = new Logger()
const pageName = TRACER_PAGES['partRefund']
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isShow: false,
    orderDetail: {},
    passengerList: [], // 乘客列表
    vehicleList: [], // 车辆列表
    passengerFeeObj: {}, // 乘客退票费用对象
    vehicleFeeObj: {}, // 车辆退票费用对象
    selectedPassengerCount: 0,
    selectedVehicleCount: 0,
    totalFee: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getOrder(options)
  },

  onShow: function() {
    setPage(pageName, PRODUCT_CODE)
  },

    /**
     * 初始化数据——乘客列表、车辆列表
     * (数据来源于订单详情页的Model)
     * @param {Any} orderDetail 订单详情
     * @param {Any} refundRules 退票规则
     */
    initState (orderDetail, refundRules) {
        const that = this
        const ticketFeeList = refundRules.TicketFeeList //退票手续费列表
        const passengerList = this.getFormatPassengerList(orderDetail)
        const vehicleList = this.getFormatVehicleList(orderDetail)

        let passengerFeeObj = {} // 乘客退票费用对象
        let vehicleFeeObj = {} // 车辆退票费用对象
        if (ticketFeeList) {
            passengerFeeObj = this.getPassengerFeeObj(ticketFeeList)
            vehicleFeeObj = this.getVehicleFeeObj(ticketFeeList)
        }

        this.setData({
            passengerFeeObj,
            vehicleFeeObj
        }, () => {
            that.computedCount(passengerList, vehicleList)
        })
    },
  
  getOrder: function({serialId}) {
    const that = this
    if(!serialId) return
    const percent = that.data.percent
    return getOrderApi({serialId}).then(response => {

        let orderDetail = cleanOrderData(response)

        that.getCanRefundConf(orderDetail).then(refundRules => {
            that.initState(orderDetail, refundRules)
        })

        this.setData({
            orderDetail
        })

        return orderDetail
    })
  },

  
  getCanRefundConf: function({orderId, serialId}) {
    const that = this
    return getCanRefundConfApi({
        orderId,
        orderSerialId: serialId,
        ticketPartRefund: []
    }).then(response => {
        if(!response) return
        const canRefund = canRefundTicket(response)

        that.setData({
            canRefund,
            refundRules: response,
            refundMsg: response.PreventRefundMsg
        })
        return response
    })
    },
   /**
     * 生成格式化乘客列表（添加isSelected字段等）
     * @param {Any} orderDetail 订单详情
     * @returns {Array} 处理后的乘客列表
     */
    getFormatPassengerList (orderDetail) {
       
        let passengerList = []
        if (orderDetail.passengerList && orderDetail.passengerList.length > 0) {
            const passengerListCopy = orderDetail.passengerList // 复制乘客列表
            passengerList = passengerListCopy.map(item => {
                item.userTypeName = SHIP_PASSENGER_TYPE_ORDER[item.userType] || ''
                item.isSelected = false
                return item
            })
        }
        return passengerList
    },
    
    /**
     * 生成格式化车辆列表（添加isSelected字段等）
     * @param {Any} orderDetail 订单详情
     * @returns {Array} 处理后的车辆列表
     */
    getFormatVehicleList (orderDetail) {
        let vehicleList = []
        if (orderDetail.shipItemVehicle && orderDetail.shipItemVehicle.length > 0) {
            const vehicleListCopy = orderDetail.shipItemVehicle // 复制车辆列表
            vehicleList = vehicleListCopy.map(item => {
                item.isSelected = false
                return item
            })
        }
        return vehicleList
    },
     /**
     * 生成乘客退票费用集合
     * @param {Array} ticketFeeList 退票手续费列表
     * @returns {Any} 乘客退票手续费对象
     */
    getPassengerFeeObj (ticketFeeList) {
        // TicketType: 1是客票; 2是车票
        const passengerFeeList = ticketFeeList.filter(item => item.TicketType === 1)
        const passengerFeeObj = {}
        passengerFeeList.forEach(item => {
            passengerFeeObj[item.TicketId] = item.TicketFee
        })
        return passengerFeeObj
    },

    
    /**
     * 生成车辆退票费用集合
     * @param {Array} ticketFeeList 退票手续费列表
     * @returns {Number} 车辆退票手续费对象
     */
    getVehicleFeeObj (ticketFeeList) {
        // TicketType: 1是客票; 2是车票
        const vehicleFeeList = ticketFeeList.filter(item => item.TicketType === 2)
        const vehicleFeeObj = {}
        vehicleFeeList.forEach(item => {
            vehicleFeeObj[item.TicketId] = item.TicketFee
        })
        return vehicleFeeObj
    },
    
    /**
     * 计算给定的乘客列表退票总费用
     * @param {Array} passengerList 给定的乘客列表
     * @returns {Number} 退票总费用 
     */
    calculateTotalFeeForPassenger (passengerList, passengerFeeObj) {
        const totalFee = passengerList.reduce((total, currentItem) => {
            const fee = passengerFeeObj[currentItem.passengerId]
            return total + fee
        }, 0)
        return totalFee
    },
    
    /**
     * 计算给定的车辆列表退票总费用
     * @param {Array} vehicleList 给定的车辆列表
     * @returns {Number} 退票总费用 
     */
    calculateTotalFeeForVehicle (vehicleList, vehicleFeeObj) {
        const totalFee = vehicleList.reduce((total, currentItem) => {
            const fee = vehicleFeeObj[currentItem.vehicleId]
            return total + fee
        }, 0)
        return totalFee
    },

    selectItem: function(e) {
        const that = this
        const { passengerList, vehicleList } = this.data
        const type = e.currentTarget.dataset.type
        const index = e.currentTarget.dataset.index
        debugger
        if (type === 'passenger') {
            const passengerListCopy = passengerList // 复制乘客列表
            passengerListCopy[index].isSelected = !passengerListCopy[index].isSelected

            that.computedCount(passengerListCopy, vehicleList)
            this.setData({
                passengerList: passengerListCopy
            })
            // setVts('订单详情页', 'XQ16', `^港口航线:${orderDetail.departureInfo.departurePort}-${orderDetail.departureInfo.arrivalPort}^发船时间:${orderDetail.departureInfo.departureTime}^退票乘客:${passengerListCopy[index].name}^`)
        } else if (type === 'vehicle') {
            const vehicleListCopy = vehicleList // 复制车辆列表
            vehicleListCopy[index].isSelected = !vehicleListCopy[index].isSelected

            that.computedCount(passengerList, vehicleListCopy)
            this.setData({
                vehicleList: vehicleListCopy
            })
        } else {
            console.log('参数错误：', type)
        }
    },

    computedCount(passengerList, vehicleList) {
        const {passengerFeeObj, vehicleFeeObj} = this.data
        const selectedPassengerList = passengerList.filter(item => item.isSelected) // 已选乘客列表
        const totalFeeForPassenger = this.calculateTotalFeeForPassenger(selectedPassengerList, passengerFeeObj) // 已选乘客退票总手续费
        const selectedVehicleList = vehicleList.filter(item => item.isSelected) // 已选车辆列表
        const totalFeeForVehicle = this.calculateTotalFeeForVehicle(selectedVehicleList, vehicleFeeObj) // 已选车辆退票总手续费
        const isShow = selectedPassengerList.length + selectedVehicleList.length > 0 // 是否展示退票费用卡片 

        const totalFee = addNum(totalFeeForPassenger, totalFeeForVehicle)
        this.setData({
            isShow,
            totalFee,
            totalFeeForPassenger,
            totalFeeForVehicle,
            passengerList,
            vehicleList,
            selectedPassengerCount: selectedPassengerList.length,
            selectedVehicleCount: selectedVehicleList.length
        })
    },
    
    /**
     * 生成部分退票列表（用于退票请求的参数）
     * @param {Array} selectedPassengerList 已选乘客列表 
     * @param {Array} selectedVehicleList 已选车辆列表
     * @returns {Array} 部分退票列表
     */
    getTicketRefundList (selectedPassengerList, selectedVehicleList) {
        const ticketPartRefund = [] // 部分退票列表
        selectedPassengerList.forEach(item => {
            ticketPartRefund.push({
                ticketId: item.passengerId,
                passengerName: item.name,
                iDCard: item.idCard,
                ticketType: 0
            })
        })
        selectedVehicleList.forEach(item => {
            ticketPartRefund.push({
                ticketId: item.vehicleId,
                passengerName: '',
                iDCard: item.vehicleNo,
                ticketType: 1
            })
        })
        return ticketPartRefund
    },


    applyForRefund() {
        const { passengerList, vehicleList } = this.data

        // 儿童， 市民儿童
        const childTypeArr = [2, 24]

        const selectedPassengerList = passengerList.filter(item => item.isSelected) // 已选乘客列表
        const selectedVehicleList = vehicleList.filter(item => item.isSelected) // 已选车辆列表
        // 没被选中且可退票的乘客列表
        const notSelectedAndCanRefundPassengerList = passengerList.filter(item => !item.isSelected && item.ticketState === 0)
        // 没被选中且可退票的车辆列表
        const notSelectedAndCanRefundVehicleList = vehicleList.filter(item => !item.isSelected && item.ticketState === 0)
        // 剩余可退票的乘客，是否只有儿童
        const isOnlyChild = notSelectedAndCanRefundPassengerList.length > 0 && notSelectedAndCanRefundPassengerList.every(item => childTypeArr.includes(Number(item.userType)))
        // 乘客全部退票时，是否还有可退票的车辆
        const isOnlyVehicle = notSelectedAndCanRefundPassengerList.length === 0 && notSelectedAndCanRefundVehicleList.length > 0
        // 是否全部退票
        const isAllRefund = notSelectedAndCanRefundPassengerList.length === 0 && notSelectedAndCanRefundVehicleList.length === 0
        let ticketPartRefund = null // 部分退票列表
        // 没有勾选乘客和车辆（正常情况按钮隐藏，不会命中）

        if (selectedPassengerList.length === 0 && selectedVehicleList.length === 0) {
            wx.showToast({
                title: '请选择需要退票的乘客或车辆',
                icon: 'none',
                mask: true
            })
            return
        }
        // 剩余可退票的乘客，不能全部都是儿童；乘客全部退票时，不能剩下可退票的车辆
        if (isOnlyChild || isOnlyVehicle) {
            wx.showModal({
                // title: '退票失败',
                content: '订单中必须包含最少一张成人票或长者票',
                confirmColor: '#00C777',
                confirmText: '知道了',
                showCancel: false
            })
            return
        }
        // 如果不是全部退票，生成部分退票列表
        // if (!isAllRefund) {
            ticketPartRefund = this.getTicketRefundList(selectedPassengerList, selectedVehicleList)
        // }
        this.refund(ticketPartRefund)
        // setVts('订单详情页', 'XQ17', '')
    },

    refund(ticketPartRefund) {
        const { orderDetail } = this.data
        const params = {
            orderId: orderDetail.orderId,
            orderSerialId: orderDetail.serialId
        }
        if (ticketPartRefund) {
            params.ticketPartRefund = ticketPartRefund
        }

        wx.showLoading({
            title: '退票中...',
            mask: true
        })
        refundTicketApi(params).then(response => {

            if(response.status !== 200) {
                return
            }

            const result = response.data

            wx.hideLoading()
            if (result && result.Code === 10000) {
                debugger
                wx.showModal({
                    title: '申请退票结果',
                    content: '退票申请成功，请等待系统处理',
                    showCancel: false,
                    confirmText: '知道了',
                    confirmColor: '#00C777',
                    success: function(res) {
                        if (res.confirm) {
                            wx.navigateBack()
                        }
                    }
                })
            } else {
                wx.showModal({
                    title: '申请退票结果',
                    content: '抱歉，退票申请失败!',
                    showCancel: false,
                    confirmText: '知道了',
                    confirmColor: '#00C777'
                })
            }
        })
        .catch(error => {
            wx.hideLoading()
            console.log(error)
        })

    }
})